package main

import (
	"context"
	"fmt"
	ezToken "gitee.com/jinmingzhi/eth-learn/5day/build"
	"gitee.com/jinmingzhi/eth-learn/pkg/ethtool"
	"github.com/ethereum/go-ethereum/accounts/abi/bind"
	"github.com/ethereum/go-ethereum/common"
	"math/big"
	"time"
)

var (
	contractAddressHex = "0xCfEB869F69431e42cdB54A4F4f105C19C080A601"
	ownerPriKey        = "0x4f3edf983ac636a65a842ce7c78d9aa706d3b113bce9c46f30d7d21715b23b1d"
	toAddressHex       = "0xe03ea8624C8C5987235048901fB614fDcA89b117"

	client *ethtool.Client
	ctx    = context.Background()
)

func main() {
	var err error
	client, err = ethtool.Dial("http://localhost:8545")
	assert(err)

	contractAddress := common.HexToAddress(contractAddressHex)
	inst, err := ezToken.NewEzToken(contractAddress, client)
	assert(err)

	credential, err := ethtool.HexToCredential(ownerPriKey)
	assert(err)

	go func() {

		chainId, err := client.NetVersion(ctx)
		assert(err)

		txOps, err := bind.NewKeyedTransactorWithChainID(credential.PrivateKey, chainId)
		assert(err)
		timer := time.NewTicker(time.Second * 5)
		for range timer.C {
			tx, err := inst.Transfer(txOps, common.HexToAddress(toAddressHex), big.NewInt(200))
			assert(err)
			fmt.Println("tx:", tx.Hash().Hex())
		}
	}()

	events := make(chan *ezToken.EzTokenTransfer)
	form := []common.Address{credential.Address}
	to := []common.Address{contractAddress}
	sub, err := inst.WatchTransfer(&bind.WatchOpts{}, events, form, to)
	assert(err)

	for {
		select {
		case err := <-sub.Err():
			panic(err)
		case event := <-events:
			fmt.Println("event:", event)
		}

	}

	time.Sleep(time.Minute)
}

func assert(err error) {
	if err != nil {
		panic(err)
	}
}
